<?php
namespace app\task\behavior;

use think\Cache;
use app\task\model\Setting;
use app\task\model\Order as OrderModel;
use app\task\model\OrderDelivery as OrderDeliveryModel;
use app\task\model\Table as TableModel;

/**
 * 订单行为管理
 */
class Order
{
    private $model;

    /**
     * 执行函数
     */
    public function run($model)
    {
        if (!$model instanceof OrderModel) {
            return new OrderModel and false;
        }
        $this->model = $model;
		//判断是否获取到”task_space_order“
        if (!Cache::has('task_space_order')) {
            $config = Setting::getItem('trade');
            // 未支付订单自动关闭
            $this->close($config['order']['close_time']);
            // 待配送订单自动配送完成(扫码)
            $this->table($config['order']['delivery_time']);
            // 待配送订单自动配送完成(排号)
            $this->row($config['order']['delivery_time']);
            // 待配送订单自动配送完成(外卖)
            $this->waimai($config['order']['delivery_time']);
            // 待配送订单自动配送完成(自取)
            $this->ziqu($config['order']['delivery_time']);
            //配送完成订单用户自动确认收货
            $this->receive($config['order']['receive_time']);
            //收货订单自动评价
            $this->cmt($config['order']['cmt_time']);
            // 退款订单自动退款
            $this->refund($config['order']['refund_time']);
            Cache::set('task_space_order', time(), $config['order']['time']*60);//有效期N分钟
        }
        return true;
    }

    /**
     * 退款订单自动完成退款
     */
    private function refund($refund_time)
    {
        if ($refund_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$refund_time * 60); //分钟
        //条件
        $filter = [
            'pay_status' => 20,
            'receipt_status' => 10,
            'refund_status' => 10,
            'order_status' => 40,
            'refund_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('refund', [
                'refund_time' => (int)$refund_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                $order->refund(1);//同意退款
            }
        }
        return true;
    }

     /**
     * 未支付订单自动关闭
     */
    private function close($close_time)
    {
        // 取消n小时以前的的未付款订单
        if ($close_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$close_time * 60);   //分钟
        // 条件
        $filter = [
            'pay_status' => 10,
            'order_status' => 10,
            'create_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 记录日志
        $this->dologs('close', [
            'close_time' => (int)$close_time,
            'deadline_time' => $deadlineTime,
            'orderIds' => json_encode($orderIds),
        ]);

        // 直接更新
        if (!empty($orderIds)) {
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                if($order['table_id'] > 0 AND $order['order_mode']['value'] == 10){
                    $table = TableModel::get($order['table_id']);
                    $table->status = 10;
                    $table->save();
                }
                $order->save(['order_status' => 20]);
            }
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（堂食扫码）
     */
    private function table($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //堂食扫码
        $filter = [
            'order_mode' => 10,
            'row_no' => ['=',''], //不是排号
            'pay_status' => ['>',10], //支持后付款
            'shop_status' => 20, //商家已接单
            'delivery_status' => 10,
            'order_status' => 10,
            'shop_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('delivery_table', [
                'delivery_time' => (int)$delivery_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //循环发送配送完成订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                post_tpl('finish',$orderIds[$n]);
            }
            return $this->model->isUpdate(true)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ], ['order_id' => ['in', $orderIds]]);
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（堂食排号）
     */
    private function row($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 10,
            'row_no' => ['<>',''],
            'pay_status' => ['>',10], //支持后付款
            'shop_status' => 20,
            'delivery_status' => 10,
            'order_status' => 10,
            'shop_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('delivery_row', [
                'delivery_time' => (int)$delivery_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //循环发送取餐提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                post_tpl('take',$orderIds[$n]);
            }
            return $this->model->isUpdate(true)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ], ['order_id' => ['in', $orderIds]]);
        }
        return true;
    }

    /**
     * 待配送订单自动配送完成（外卖）
     */
    private function waimai($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 20,
            'pay_status' => ['>',10], //支持后付款
            'shop_status' => 30,
            'delivery_status' => 20,
            'order_status' => 10,
            'delivery_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('delivery_waimai', [
                'delivery_time' => (int)$delivery_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //循环发送配送完成提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                post_tpl('delivery',$orderIds[$n]);
            }
            $deliveryModel = new OrderDeliveryModel;
            $deliveryModel->isUpdate(true)->save([
                'delivery_status' => 50,
                'delivery_time' => time()
            ], ['order_id' => ['in', $orderIds]]);
            return $this->model->isUpdate(true)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ], ['order_id' => ['in', $orderIds]]);
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（自取）
     */
    private function ziqu($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 30,
            'pay_status' => ['>',10], //支持后付款
            'shop_status' => 20,
            'delivery_status' => 10,
            'order_status' => 10,
            'arrive_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('delivery_ziqu', [
                'delivery_time' => (int)$delivery_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //循环发送取餐提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                post_tpl('take',$orderIds[$n]);
            }
            return $this->model->isUpdate(true)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ], ['order_id' => ['in', $orderIds]]);
        }
        return true;
    }

    /**
     * 已配送订单自动确认收货
     */
    private function receive($receive_time)
    {
        if ($receive_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$receive_time * 60); //分钟
        //条件
        $filter = [
            'pay_status' => 20, //非后付费有效
            'delivery_status' => 30,
            'receipt_status' => 10,
            'order_status' => 10,
            'delivery_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('receive_tang_ziqu', [
                'receive_time' => (int)$receive_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //循环发送完成订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                post_tpl('finish',$orderIds[$n]);
            }
            //更新餐桌状态
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                if($order['table_id']>0){
                    $table = TableModel::get($order['table_id']);
                    $table->status = 10;
                    $table->save();
                }
            }
            $this->model->isUpdate(true)->save([
                'receipt_status' => 20,
                'receipt_time' => time(),
                'order_status' => 30
            ], ['order_id' => ['in', $orderIds]]);
        }
        return true;
    }

    /**
     * 已收货订单自动评价
     */
    private function cmt($cmt_time)
    {
        if ($cmt_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$cmt_time * 60); //分钟
        //条件
        $filter = [
            'is_cmt' => 0,
            'receipt_status' => 20,
            'order_status' => 30,
            'receipt_time' => ['<', $deadlineTime]
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            // 记录日志
            $this->dologs('cmt', [
                'receive_time' => (int)$cmt_time,
                'deadline_time' => $deadlineTime,
                'orderIds' => json_encode($orderIds),
            ]);
            //更新餐桌状态
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                $order->comment()->save([
                    'serve' => 5,
                    'speed' => 5,
                    'flavor' => 5,
                    'ambient' => 5,
                    'user_id' => isset($order['user_id'])?:$order['user_id'],
                    'shop_id' => $order['shop_id'],
                    'wxapp_id' => $order['wxapp_id']
                ]);
                $order->save(['is_cmt' => 1]);
            }
        }
        return true;
    }

    /**
     * 记录日志
     */
    private function dologs($method, $params = [])
    {
        $value = 'Order --' . $method;
        foreach ($params as $key => $val)
            $value .= ' --' . $key . ' ' . $val;
        return write_log($value, __DIR__);
    }

}
